/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package towerz.game.entity.tower;

import java.util.Hashtable;
import towerz.system.Utilities;
import towerz.system.xml.XmlNode;
import towerz.system.xml.XmlReaderWriter;

/**
 *
 * @author LegACy
 */
public class TowerFactory {
	protected TowerFactory() {
		//Initialize
		m_BuffDictionary	= new Hashtable();
		m_TowerDictionary	= new Hashtable();

		//Load tower file
		XmlNode XML = XmlReaderWriter.getInstance().readFromXmlFile(Utilities.TOWERDATA_FOLDER + "/data.xml");

		//For each child
		for (int i = 0; i < XML.getChildren().size(); i++) {
			//Get child
			XmlNode Child = (XmlNode)XML.getChildren().elementAt(i);

			//Check name
			if (Child.getNodeName().equals("tower")) {
				//Save to dictionary
				int Index = Integer.parseInt(Child.getAttribute("index"));
				if (Index >= 0) m_TowerDictionary.put(new Integer(Index), new TowerData(Child));
			}
		}
		
		//Load description
		m_DescriptionXML = XmlReaderWriter.getInstance().readFromXmlFile(Utilities.TOWERDATA_FOLDER + "/desc.xml");
		loadDescription();
        
        //Load buffs.xml file
        XML = XmlReaderWriter.getInstance().readFromXmlFile(Utilities.BUFFDATA_FILE);
        
        //For each child
		for (int i = 0; i < XML.getChildren().size(); i++) {
			//Get child
			XmlNode Child   = (XmlNode)XML.getChildren().elementAt(i);
            
            //Insert to hashtable
            m_BuffDictionary.put(Integer.valueOf(Child.getAttribute("index")), Child) ;
		}
	}

	public synchronized static TowerFactory instance() {
		//Create state manager if doesn't exist
		if (s_Instance == null) {
            s_Instance = new TowerFactory();
        }
		
        return s_Instance;
	}
	
	public void loadDescription() {
		//For each child
		for (int i = 0; i < m_DescriptionXML.getChildren().size(); i++) {
			//Get child
			XmlNode Child = (XmlNode)m_DescriptionXML.getChildren().elementAt(i);

			//Check name
			if (Child.getNodeName().equals("tower")) {
				//Get data
				int Index		= Integer.parseInt(Child.getAttribute("index"));
				TowerData Data	= getTowerData(Index);
				//Reload if not null
				if (Data != null) Data.loadDescription(Child);
			}
		}
	}

	public int getTowerNumber() {
		return m_TowerDictionary.size() + 1;
	}

	public TowerData getTowerData(int index) {
		return (TowerData)m_TowerDictionary.get(new Integer(index));
	}

	public XmlNode getBuffData(int index) {
		return (XmlNode)m_BuffDictionary.get(new Integer(index));
	}

	//The only instance
	private static TowerFactory s_Instance = null;

	//Dictionary
	XmlNode		m_DescriptionXML;
	Hashtable	m_BuffDictionary;
	Hashtable	m_TowerDictionary;
}
